package com.jzm.controller;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.jzm.annotation.AutoWried;
import com.jzm.annotation.PostMapping;
import com.jzm.annotation.ReqeustMapping;
import com.jzm.dto.ResDTO;
import com.jzm.dto.UserQueryDTO;
import com.jzm.entity.User;
import com.jzm.service.UserService;
import com.jzm.utils.JwtUtil;
import com.jzm.utils.MD5Util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@ReqeustMapping(value = "/user")
public class UserController {
    private static final Cache<String, String> cache = Caffeine.newBuilder()
            .maximumSize(1000)
            .expireAfterWrite(1, TimeUnit.MINUTES)
            .build();

    @AutoWried
    private UserService userService;

    /**
     * 创建用户
     *
     * @param user
     * @return
     */
    @PostMapping(value = "/createUser")
    public User createUser(User user) throws Exception {
        //幂等
        String key = MD5Util.encrypt(user.toString());
        if (cache.getIfPresent(key) != null) {
            return null;
        } else {
            cache.put(key,"");
            return this.userService.createUser(user);
        }
    }

    /**
     * 修改用户信息
     *
     * @param user
     * @return
     */
    @PostMapping(value = "/updateUser")
    public User updateUser(User user) {
        return this.userService.updateUser(user);
    }

    /**
     * 查询用户列表
     *
     * @param userQueryDTO
     * @return
     */
    @PostMapping(value = "/selectUserInfo")
    public List<User> selectUserInfo(UserQueryDTO userQueryDTO) {
        return this.userService.selectUserInfo(userQueryDTO);
    }

    /**
     * 查询用户列表
     *
     * @return
     */
    @PostMapping(value = "/login")
    public ResDTO selectUserInfo(User user) {
        //登录校验 DB
        ResDTO resDTO = null;
        if (true) {
            resDTO = new ResDTO();
            resDTO.setCode(200);
            Map<String, String> tokenMap = new HashMap<>();
            tokenMap.put("token", JwtUtil.generateToken(user.getUserName()));
            resDTO.setData(tokenMap);
        }
        return resDTO;
    }
}
